package com.toilet.easyvideo.security;

import cn.hutool.json.JSONUtil;
import com.toilet.easyvideo.constant.HttpStatus;
import com.toilet.easyvideo.constant.StringConstant;
import com.toilet.easyvideo.handler.ResponseResult;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.AuthorizationServiceException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.csrf.CsrfException;

import java.io.IOException;

public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        if (accessDeniedException instanceof CsrfException) {
            returnResponse(response, "非法访问跨域请求异常!");
            return;
        } else if (accessDeniedException instanceof AuthorizationServiceException) {
            returnResponse(response, "认证服务异常请重试!");
            return;
        } else if (accessDeniedException != null) {
            returnResponse(response, "权限不足不允许访问!");
            return;
        }
        returnResponse(response, accessDeniedException.getMessage());
    }

    private void returnResponse(HttpServletResponse response, String errorMsg) throws IOException {
        response.setCharacterEncoding(StringConstant.UTF8);
        ResponseResult result = new ResponseResult(HttpStatus.FORBIDDEN, errorMsg);
        response.getWriter().write(JSONUtil.toJsonStr(result));
    }
}
